import 'package:flutter/material.dart';
import 'package:kiomax/utils/screen_util.dart';
import '../../config/color_config.dart';

class DropdownSelectItem {
  final String title;
  final IconData? icon;
  final VoidCallback? onTap;

  DropdownSelectItem({
    required this.title,
    this.icon,
    this.onTap,
  });
}

class DropdownSelect extends StatefulWidget {
  final String label;
  final String hint;
  final List<DropdownSelectItem> items;
  final ValueChanged<DropdownSelectItem?>? onChanged;
  final DropdownSelectItem? value;
  final TextEditingController? searchController;
  final bool showSearch;
  final String? searchHint;

  const DropdownSelect({
    Key? key,
    required this.label,
    required this.hint,
    required this.items,
    this.onChanged,
    this.value,
    this.searchController,
    this.showSearch = false,
    this.searchHint,
  }) : super(key: key);

  @override
  State<DropdownSelect> createState() => _DropdownSelectState();
}

class _DropdownSelectState extends State<DropdownSelect> {
  final GlobalKey _key = GlobalKey();
  OverlayEntry? _overlayEntry;
  bool _isOpen = false;

  @override
  void dispose() {
    _removeOverlay();
    super.dispose();
  }

  void _removeOverlay() {
    if (_overlayEntry != null) {
      _overlayEntry?.remove();
      _overlayEntry = null;

      // Don't call setState here if this method is called during dispose
      if (mounted) {
        setState(() {
          _isOpen = false;
          // only update UI if still mounted
        });
      }
    }
  }

  void _toggleDropdown() async {
    if (_isOpen) {
      _removeOverlay();
    } else {
      final RenderBox? renderBox =
          _key.currentContext?.findRenderObject() as RenderBox?;
      if (renderBox == null) return;

      final size = renderBox.size;
      final offset = renderBox.localToGlobal(Offset.zero);

      _overlayEntry = _createOverlayEntry(size, offset);
      Overlay.of(context).insert(_overlayEntry!);
      setState(() {
        _isOpen = true;
      });
    }
  }

  OverlayEntry _createOverlayEntry(Size size, Offset offset) {
    return OverlayEntry(
      builder: (context) => Stack(
        children: [
          // 背景遮罩
          Positioned.fill(
            child: GestureDetector(
              onTap: _removeOverlay,
              behavior: HitTestBehavior.opaque,
              child: Container(
                color: Colors.transparent,
              ),
            ),
          ),
          // 下拉框
          Positioned(
            left: offset.dx,
            // top: offset.dy + size.height - 4,
            top: offset.dy,
            width: size.width,
            child: Material(
              color: Colors.transparent,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(Radius.circular(20)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                constraints: BoxConstraints(
                  maxHeight: MediaQuery.of(context).size.height * 0.4,
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8.0),
                      width: size.width,
                      child: _getRowWidgetList(),
                    ),
                    if (widget.showSearch)
                      Container(
                        padding: const EdgeInsets.all(8.0),
                        width: size.width,
                        child: TextField(
                          controller: widget.searchController,
                          decoration: InputDecoration(
                            hintText: widget.searchHint ?? 'Search...',
                            prefixIcon: const Icon(Icons.search,
                                color: ColorConfig.searchIconColor),
                            hintStyle: const TextStyle(
                              color: ColorConfig.searchHintColor,
                              fontSize: 16,
                            ),
                            filled: true,
                            fillColor: ColorConfig.searchBackground,
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(35),
                              borderSide: BorderSide.none,
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                                horizontal: 16, vertical: 12),
                          ),
                        ),
                      ),
                    Flexible(
                      child: ListView.builder(
                        padding: EdgeInsets.zero,
                        shrinkWrap: true,
                        itemCount: widget.items.length,
                        itemBuilder: (context, index) {
                          final item = widget.items[index];
                          return InkWell(
                            onTap: () {
                              if (item.onTap != null) {
                                item.onTap!();
                              } else {
                                widget.onChanged?.call(item);
                              }
                              _removeOverlay();
                            },
                            child: Container(
                              width: size.width,
                              padding: const EdgeInsets.symmetric(
                                  horizontal: 16, vertical: 12),
                              child: Row(
                                children: [
                                  if (item.icon != null) ...[
                                    Icon(item.icon,
                                        color: ColorConfig.primary, size: 24),
                                    const SizedBox(width: 12),
                                  ] else
                                    const Icon(Icons.location_on_outlined,
                                        color: ColorConfig.primary, size: 24),
                                  Expanded(
                                    child: Text(
                                      item.title,
                                      style: const TextStyle(
                                        color: ColorConfig.textPrimary,
                                        fontSize: 16,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(
          width: ScreenUtil.setWidth(80),
          child: Text(
            widget.label,
            style: const TextStyle(
              color: ColorConfig.textPrimary,
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        const SizedBox(width: 8),
        Flexible(
          child: Container(
            key: _key,
            child: InkWell(
              onTap: _toggleDropdown,
              child: Container(
                height: 48,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(80),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 8,
                      offset: const Offset(0, 4),
                    ),
                  ],
                  color: Colors.white,
                ),
                child: _getRowWidgetList(),
              ),
            ),
          ),
        ),
      ],
    );
  }

  _getRowWidgetList() {
    return InkWell(
      onTap: _toggleDropdown,
      child: Row(
        children: [
          const Icon(
            Icons.location_on_outlined,
            size: 24,
            color: ColorConfig.primary,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Text(
              widget.value?.title ?? widget.hint,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: widget.value != null
                    ? ColorConfig.textPrimary
                    : ColorConfig.searchHintColor,
                fontSize: 16,
              ),
            ),
          ),
          Icon(
            _isOpen
                ? Icons.keyboard_arrow_up
                : Icons.keyboard_arrow_down,
            color: ColorConfig.searchIconColor,
          ),
        ],
      ),
    );
  }
}
